package com.gzw.jackyweather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.gzw.jackyweather.db.CityManger;
import com.gzw.jackyweather.gson.Weather;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.List;

public class MainActivity extends BaseActivity {

    private ChooseAreaFragment fragment;

    private long exitTime = 0;

    @Override
    public int getContentViewID() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

        fragment = new ChooseAreaFragment();
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fl, fragment);
        ft.commit();

        //如果已经看过某个城市的天气了，就直接跳转到显示天气的界面
        List<CityManger> mangers = DataSupport.where("isDefault = ?", "1").find(CityManger.class);

        if (mangers.size() != 0) {
            Intent intent = new Intent(this, WeatherActivity.class);
            startActivity(intent);
            finish();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if (Contans.CURRENTLEVEL == Contans.LEVEL_COUNTY) {//如果在县，返回城市
                fragment.queryCities();
            } else if (Contans.CURRENTLEVEL == Contans.LEVEL_CITY) {//如果在城市，返回省
                fragment.queryProvinces();
            } else if (Contans.CURRENTLEVEL == Contans.LEVEL_PROVINCE) {//如果在省，按两下退出程序
                if (System.currentTimeMillis() - exitTime > 2000) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
//                    Toast.makeText(this, "退出程序", Toast.LENGTH_SHORT).show();
                    System.exit(0);
                    finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
